<template>
  <el-dropdown trigger="click" @command="handleCommand">
    <div class="announcement-notification">
      <el-badge :value="unreadCount" :max="99" class="item">
        <i class="el-icon-bell"></i>
      </el-badge>
    </div>
    <el-dropdown-menu slot="dropdown" class="announcement-dropdown">
      <div class="announcement-dropdown-header">
        <span>公告通知</span>
        <el-button type="text" @click.stop="viewAllAnnouncements">查看全部</el-button>
      </div>
      <el-divider></el-divider>
      <div v-if="announcements.length === 0" class="announcement-empty">
        暂无公告
      </div>
      <el-dropdown-item v-for="item in announcements" :key="item.id" :command="item.id">
        <div class="announcement-item">
          <div class="announcement-title">
            {{ item.title }}
            <el-tag v-if="!item.hasRead" type="warning" size="mini">未读</el-tag>
          </div>
          <div class="announcement-meta">
            <span>{{ item.publisherName }}</span>
            <span>{{ item.publishTime | parseTime('{y}-{m}-{d}') }}</span>
          </div>
        </div>
      </el-dropdown-item>
    </el-dropdown-menu>
  </el-dropdown>
</template>

<script>
import { getUserAnnouncements } from '@/api/announcement/index'

export default {
  name: 'AnnouncementNotification',
  data() {
    return {
      announcements: [],
      unreadCount: 0
    }
  },
  created() {
    this.fetchAnnouncements()
    // 定时刷新公告
    this.timer = setInterval(this.fetchAnnouncements, 5 * 60 * 1000)
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    fetchAnnouncements() {
      getUserAnnouncements().then(response => {
        // 只显示最近的5条公告
        this.announcements = response.data.slice(0, 5)
        this.unreadCount = response.data.filter(item => !item.hasRead).length
      })
    },
    handleCommand(id) {
      this.$router.push(`/announcement/detail/${id}`)
    },
    viewAllAnnouncements() {
      this.$router.push('/announcement/center')
    }
  }
}
</script>

<style scoped>
.announcement-notification {
  height: 50px;
  line-height: 50px;
  margin-right: 30px;
  cursor: pointer;
}
.announcement-notification i {
  font-size: 20px;
  vertical-align: middle;
}
.announcement-dropdown {
  width: 350px;
  padding: 0;
}
.announcement-dropdown-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  font-size: 16px;
  font-weight: bold;
}
.announcement-empty {
  padding: 20px;
  text-align: center;
  color: #999;
}
.announcement-item {
  padding: 5px 0;
}
.announcement-title {
  font-size: 14px;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.announcement-meta {
  font-size: 12px;
  color: #999;
  display: flex;
  justify-content: space-between;
}
</style> 